<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="消息状态" prop="readStatus">
        <el-select v-model="queryParams.readStatus" clearable>
          <el-option v-for="item, index in messageStatus" :key="index" :label="item" :value="index"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="消息标题" prop="title">
        <el-input v-model="queryParams.title" placeholder="消息标题" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <!-- <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          clearable
          v-model="queryParams.createTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择创建时间"
        >
        </el-date-picker>
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-edit" size="mini" @click="setReads(0)"
          :disabled="!ids.length">标记未读</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-edit" size="mini" @click="setReads(1)"
          :disabled="!ids.length">标记已读</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-edit" size="mini" @click="handleSetAllRead">全部已读</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>

    </el-row>



    <el-tabs v-model="tabName" @tab-click="tabClick">
      <el-tab-pane label="全部" name="all"></el-tab-pane>
      <el-tab-pane v-for="(item, key) in notify" :key="item.text" :label="item.text + '(' + item.num + ')'" :name="key">
      </el-tab-pane>
    </el-tabs>

    <el-table v-loading="loading" :data="centerList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="通知标题" align="center" prop="title">
        <template slot-scope="scope">
          <span v-if="0 == scope.row.readStatus" class="circle" style="background: red"></span>
          <span>{{ scope.row.title }}</span>
        </template>
      </el-table-column>
      <el-table-column label="通知类型" align="center" prop="noticeType">

        <template slot-scope="scope">
          <span>{{ noticeType[scope.row.noticeType] }}</span>
        </template>
      </el-table-column>
      <el-table-column label="通知内容" align="center" prop="noticeContent" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">

        <template slot-scope="scope">
          <span>{{ scope.row.createTime | timestampToDate }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">

        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['center:center:edit']">立即查看</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />
  </div>
</template>

<script>
import {
  listCenter,
  delCenter,
  addCenter,
  updateCenter,
  listStatics,
  setAllRead
} from "@/api/center/center";
import {
  NOTIFICATIONS,
  NOTIFICATIONS_NUMBER,
  NOTIFICATIONS_URL,
  MESSAGE_STATUS
} from "@/constant/const";
import { NoticeCenterList } from "@/jscomponent/notice.component";
import { timestampToDate } from "@/utils/time";
import request from "@/utils/request";
import { listManager } from "@/api/service-manager/manager";
import { sleep } from "@/utils/sleep";
export default {
  name: "Center",
  filters: {
    timestampToDate,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      notify: { ...NOTIFICATIONS_NUMBER },
      // 选中数组
      ids: [],
      tabName: "all",
      // 非单个禁用
      single: true,
      /**
       * @param {NoticeCenterList}
       */
      noticeInstance: undefined,
      // 非多个禁用
      multiple: true,
      noticeType: NOTIFICATIONS,
      messageStatus: MESSAGE_STATUS,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 通知中心表格数据
      centerList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      isSuperAdmin: false,
      isEdit: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        createTime: null,
      },
      isSearch: false
    };
  },
  created() {
    this.isSuperAdmin = this.$store.getters.roles.some(item => ["admin", "tyadmin"].includes(item));
    this.isEdit = this.$store.getters.roles.some(item => ["order:manager:edit"].includes(item));
    for (let key in this.notify) {
      let show = this.notify[key].isAdmin;
      if (true == show && show != this.isSuperAdmin) {
        delete this.notify[key];
      }
    }
    this.getList();
    this.noticeInstance = new NoticeCenterList(this);
  },

  mounted() {
    this.countNumber();
  },
  methods: {

    countNumber() {
      listStatics().then((res) => {
        let data = res.data;
        let key = "";
        for (let i = 0; i < data.length; i++) {
          key = data[i].orderNotice;

          let val = this.notify[key];

          if (!val) {
            continue;
          }
          val.num = data[i].num;
        }
      });
    },

    /** 查询通知中心列表 */
    getList() {
      let params = {};
      if (this.isSearch) {
        params = Object.assign({}, this.queryParams)
      } else {
        params = {
          pageNum: this.queryParams.pageNum,
          pageSize: this.queryParams.pageSize
        }
      }
      if (this.tabName !== 'all') {
        this.tabClick();
        return;
      }
      this.loading = true;
      listCenter(params).then((response) => {
        this.centerList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    tabClick() {
      /**
       * @param {Function} method
       */
      let method = NoticeCenterList.prototype[this.tabName];
      if (!method) {
        return;
      }
      method.apply(this.noticeInstance);
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        userId: null,
        adminId: null,
        noticeType: null,
        typeId: null,
        readStatus: null,
        title: null,
        noticeContent: null,
        createTime: null,
        updateTime: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.isSearch = true;
      this.tabName = 'all'
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.isSearch = false;
      this.queryParams.pageNum = 1;
      this.tabName = 'all';
      this.getList()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加通知中心";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.setRead(row.id, 1)
      let res = NOTIFICATIONS_URL[row.noticeType];

      if (this.isSuperAdmin) {
        if (row.title === "派稿通知") {
          this.$router.push('/editOrder');
          return;
        }
        if (res.requestURL) {
          request({
            url: res.requestURL + "/" + row.typeId,
            method: "get"
          }).then((data) => {
            listManager({
              pageNum: 1,
            }).then((response) => {
              sessionStorage.setItem(
                "managerList",
                JSON.stringify(response.rows)
              );

              sessionStorage.setItem("orderItem", JSON.stringify(data.data));
              this.$router.push(res.url + "/" + row.typeId)
            });
          });
        } else {
          this.$router.push(res.url)
        }
        return;
      } else if (this.isEdit) {
        this.$store.commit("SET_ORDER_SNID", row.typeId)
        this.$router.push('/editOrder');
      } else {
        if (!res.editURL) {
          return;
        }
        this.$router.push(res.editURL + "?id=" + row.typeId)

      }


    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateCenter(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCenter(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    commonRead(id, status) {
      return new Promise((resolve, reject) => {
        updateCenter({
          id: id,
          readStatus: status
        }).then(async (response) => {
          resolve(response)
        }).catch(error => {
          reject(error)
        })

      });
    },

    // 设置已读未读
    setRead(id, status) {
      this.commonRead(id, status);
      this.getList();
    },

    //设置全部已读
    handleSetAllRead() {
      setAllRead().then(async (response) => {
        await this.countNumber();
        this.getList();
      })
     
    },

    // 标记已读/未读轮询
    setReads(status) {
      Promise.all(this.ids.map(async (item) => {
        await this.commonRead(item, status);
        await sleep(300);
      })).finally(async () => {
        this.getList()
      })
    },


    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除通知中心编号为"' + ids + '"的数据项？')
        .then(function () {
          return delCenter(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "center/center/export",
        {
          ...this.queryParams,
          ids: this.ids.length ? this.ids : undefined
        },
        `center_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>

<style scoped>
.circle {
  position: absolute;
  top: 17px;
  left: 4px;
  width: 12px;
  height: 12px;
  border-radius: 50%;
  margin-right: 5px;
}

.hover-style-left {
  height: 40px;
  min-width: 200px;
  padding: 10px;
  display: none;
  color: #faab00;
  text-align: center;
  line-height: 40px;
  font-size: 14px;
  border: 1px solid #ffdd81;
  background: #fff8f0;
  position: absolute;
  z-index: 10;
  box-shadow: 0px 2px 4px 0px rgba(226, 199, 46, 0.18);
  border-radius: 4px;
}

.hover-style-left:after,
.hover-style-left:before {
  content: "";
  position: absolute;
  width: 0;
  height: 0;
  font-size: 0;
  line-height: 0;
  border-width: 10px;
  top: 19px;
  left: -21px;
  border-style: solid dashed dashed solid;
  border-color: transparent #ffdd81 transparent transparent;
}

.hover-style-left:after {
  left: -20px;
  border-color: transparent #fff8f0 transparent transparent;
}
</style>
